$(function() {
	//初始化，检查是否有保存登录数据
	function init() {
		var userInfo = JSON.parse(localStorage.getItem('userInfo'));
		if(userInfo) {
			$('#username').val(userInfo.principal);
			$('#password').val(userInfo.password);
			if(userInfo.type == 0) {
				merchantLogin(userInfo.principal, userInfo.password)
			} else if(userInfo.type == 1) {
				insideLogin(userInfo.principal, userInfo.password)
			}
		}
	}
	init();

	$('.inputview ul li').click(function() {
		$(this).addClass('active').siblings().removeClass('active');
	})
	//商户登录
	function merchantLogin(user, pwd) {
		var authen = {
			principal: user,
			password: pwd
		}
		var userdata = {
			principal: user,
			password: pwd,
			type: 0
		}
		var d = JSON.stringify(userdata);
		$.ajax({
			url: "tenantlogin.thor",
			data: authen,
			cache: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				var data = JSON.stringify(data);
				console.log("response: " + JSON.stringify(data));
				layer.msg("登录成功");
				window.localStorage.setItem('loginInfo', data);
				window.localStorage.setItem('userInfo', d);
				window.location.href = "tobill.thor";
			},
			error: function(data) {
				layer.msg("用户名或密码错误")

			}
		});
	}
	//内部登录
	function insideLogin(user, pwd) {
		var authen = {
			principal: user,
			password: pwd
		}
		var userdata = {
			principal: user,
			password: pwd,
			type: 1
		}
		var d = JSON.stringify(userdata);
		$.ajax({
			url: "marketlogin.thor",
			data: authen,
			cache: false,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			success: function(data) {
				console.log("response: " + JSON.stringify(data));
				var data = JSON.stringify(data);
				window.localStorage.setItem("loginInfo", data);
				window.localStorage.setItem('userInfo', d);
				window.location.href = "tobill.thor";
			},
			error: function(data) {
				var data = JSON.stringify(data)
				layer.msg("用户名或密码错误")

			}
		});
	}
	//点击登录按钮事件
	$('#loginBtn').click(function() {
		var userName = $('#username').val(); //获取用户名
		var userPass = $('#password').val(); //获取密码
		var type = 0; //登录类别
		var reg = new RegExp('active');
		if(reg.test($('.inputview ul li').eq(0).attr('class'))) {
			type = 0;
			console.log(type)

		} else if(reg.test($('.inputview ul li').eq(1).attr('class'))) {
			type = 1;
			console.log(type)

		}
		if(userName == '' || userPass == '') {
			layer.msg("用户名或密码为空");
		} else if(type == 0) {
			merchantLogin(userName, userPass);
		} else if(type == 1) {
			insideLogin(userName, userPass);
		}
	})
})